import { _decorator, Component, Animation, AnimationClip } from "cc";
import { AnimState3 } from "./AnimState3";
import { WarroirStates } from "../../Test1/Enums/EnumPool";
const { ccclass, property } = _decorator;

@ccclass("AnimEvents3")
export class AnimEvents3 extends Component {
  @property
  anim: Animation;

  @property
  animMap: Map<string, AnimState3> = new Map();

  animationName = "AnimationTest3";
  stateClipMap: Map<string, string> = new Map();

  generateClip(state: AnimState3) {
    let clip = AnimationClip.createWithSpriteFrames(
      state.spriteFrameArray,
      state.frameRate
    );

    clip.name = state.clipName;
    clip.wrapMode = state.clipWrapMode;
    clip.duration = state.clipDuration;
    return clip;
  }

  initializedAnim(value: AnimState3) {
    this.anim = this.node.getComponent(Animation);
    this.anim.node = this.node;
    this.anim.name = this.animationName;
    this.anim.playOnLoad = true;

    // this.anim.defaultClip = this.generateClip(value);
    this.anim.addClip(this.generateClip(value));
  }

  structuredAnimations() {
    for (const [key, value] of this.animMap.entries()) {
      this.initializedAnim(value);
      this.stateClipMap.set(key, value.clipName);
    }

    console.log("AnimationTest3-anim", this.anim);
    this.stateTransition();
  }

  stateTransition(stateKey: string = WarroirStates.WARRIOR_IDLE) {
    let clipName = this.stateClipMap.get(stateKey);

    if (stateKey == WarroirStates.WARRIOR_ATTACK) {
      clipName = this.stateClipMap.get(stateKey);
      this.anim.crossFade(clipName, 0.3);
      this.anim.on(
        Animation.EventType.FINISHED,
        this.onAnimationFinished,
        this
      );
    }
    this.anim.play(clipName);
  }

  onAnimationFinished() {
    console.log("onAnimationFinished");
    this.stateTransition();
  }
}
